<template>
  <div class="body">
    <div v-if="isShowSearch">
      <van-search
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch(value)"
        @cancel="onCancel"
        @update:model-value="autoSearch"
      >
      </van-search>
      <van-cell-group>
        <van-cell @click="onclick" v-for="(item, index) in keywordList" :key="index" is-link>{{
          item
        }}</van-cell>
      </van-cell-group>
      <div class="history" v-show="historyList.length">
        <div class="text">
          历史记录
          <van-icon @click="delAll" class="del" size="20px" name="delete" />
        </div>
        <div class="historyItem">
          <van-tag
            @click="searchByvalue(item)"
            class="item"
            v-for="(item, index) in historyList"
            :key="index"
            plain
            >{{ item }}</van-tag
          >
        </div>
      </div>
      <div class="crumb">
        <div class="hot">热门搜索</div>
        <div class="crumbItem">
          <van-tag
            @click="searchByvalue(item.keyword)"
            class="item"
            :class="{ active: item.highlight === 1 }"
            v-for="(item, index) in searchList"
            :key="index"
            plain
            >{{ item.keyword }}</van-tag
          >
        </div>
      </div>
    </div>
    <SearchDetail :changeIsShowSearch="changeIsShowSearch" v-if="!isShowSearch"></SearchDetail>
  </div>
</template>
<script lang="ts">
import { computed, onMounted, ref } from "@vue/runtime-core";
import { useSearchStore } from "../../store/search";
import SearchDetail from "./component/SearchDetail.vue";
import { reqNowKeyWords} from "../../api/search/search";
import emitter from '../../../mitt/event'
export default {
  name: "Search",
  components: { SearchDetail },
};
</script>
<script lang="ts" setup>
// history数组变量
let isShowSearch = ref(true);
const historyList = ref([]);
const value = ref("");
const searchStore = useSearchStore();
const keywordList = ref([]);
// 改变要显示的页面
const changeIsShowSearch=()=>{
  isShowSearch.value=!isShowSearch.value
}
onMounted(async () => {
  // 渲染页面后获取搜索的热门搜索数据
  await searchStore.getSearchData();
  // 获取历史记录
  historyList.value = JSON.parse(localStorage.getItem("history")) || [];
  // 发布事件  监听要显示的页面
  emitter.on('changeshow',()=>{isShowSearch.value=value})
});
// 选中一条提示商品页面跳转，发送求情 并让提示框的数组为空
const onclick =async(e)=>{
  // 获取点击的内容    e.target.innerHTML
  const myinnerHTML = e.target.innerHTML
  value.value=myinnerHTML
  // 条件渲染页面
  isShowSearch.value = false
  // 保存搜索记录
  onSearch(myinnerHTML)
  // 发送请求获取详情页内容
  const res = await searchStore.getKeyWordsList(value.value)
  // 将关键字的列表清空
  keywordList.value=[]
}
//  搜索回车事件 保存搜索记录并发送请求
const onSearch = (value) => {
  console.log(value)
  // 判断记录是否有内容 没有就直接添加
  if (!historyList.value.length) {
    // 田间记录
    historyList.value.unshift(value);
    localStorage.setItem("history", JSON.stringify(historyList.value));
    // 发送请求
    searchByvalue(value)
  } else {
    // 判断是否有重复的搜索记录
    const flag = historyList.value.some((item) => item === value);
    console.log(flag);
    if (flag) {
      // 记录重复，不在记录，单还要发送请求
      searchByvalue(value)
      return;
    } else {
      // 不存在记录，要将该记录添加，并发送请求
      historyList.value.unshift(value);
      localStorage.setItem("history", JSON.stringify(historyList.value));
      searchByvalue(value)
    }
    // 改变要显示的页面
    isShowSearch.value = false
  }
};
// 实时搜索 节流搜索
// 防抖函数
// function debounce(fn, time) {
//     let timer = null;
//     return function () {
//         if (timer) {
//             clearTimeout(timer);
//             timer = null;
//         }
//         timer = setTimeout(() => {
//             fn();
//         }, time);
//     }
// }
function throttle(fn, time) {
  let isRuning = false;
  return function () {
    if (isRuning) {
      return;
    }
    isRuning = true;
    setTimeout(() => {
      fn();
      isRuning = false;
    }, time);
  };
}
// 输入内容自动搜索，并渲染数据
const autoSearch = async (value) => {
  // 获取自动搜索的关键字
  const res = await reqNowKeyWords(`keywordPrefix=${value}`);
  console.log("autosearch", res);
  // 将关键字保存方便渲染
  keywordList.value = res;

};
// 点击关键字搜索
const searchByvalue=async(keyword)=>{
  // 根据关键字发送请求
  searchStore.getKeyWordsList(keyword)
  // 改变要显示的页面
  isShowSearch.value=false
}
// 删除所有的浏览记录
const delAll = () => {
  console.log("删除");
  // 清空localStorage的内容
  localStorage.removeItem("history");
  // 本地页清空
  historyList.value = [];
};

const searchList = computed(() => searchStore.searchList.hotKeywordVOList);
</script>

<style lang="less" scoped>
.body {
  width: 100%;
  // height: 100vh;
  background-color: #aaa;
  .crumb {
    background-color: #fff;
    .hot {
      width: 93%;
      margin: auto;
      font-size: 14px;
      color: #bbb;
      margin-bottom: 15px;
    }
    .crumbItem {
      width: 93%;
      margin: auto;
      display: flex;
      flex-wrap: wrap;
      .item {
        padding: 4px;
        margin-bottom: 20px;
        margin-right: 18px;
        color: #aaa;
        &.active {
          padding: 4px;
          margin-bottom: 20px;
          margin-right: 18px;
          color: red;
        }
      }
    }
  }
  .history {
    background-color: #fff;
    margin-bottom: 8px;
    .text {
      width: 93%;
      margin: auto;
      font-size: 14px;
      color: #bbb;
      margin-bottom: 15px;
      .del {
        float: right;
      }
    }
    .historyItem {
      width: 93%;
      margin: auto;
      display: flex;
      flex-wrap: wrap;
      .item {
        padding: 4px;
        margin-bottom: 20px;
        margin-right: 18px;
        color: #aaa;
      }
    }
  }
}
</style>
